<template>
	<page-wrapper :page-path="'/pages/platform/platform'" navTitle="平台管理" :navBackgroundColor="primaryColor"
		:navTitleStyle="navTitleStyle">
		<view class="platform-container">
			<!-- 搜索筛选区 -->
			<view class="search-filter">
				<view class="search-box">
					<uni-icons type="search" size="20" color="#999"></uni-icons>
					<input type="text" v-model="searchForm.name" placeholder="搜索平台名称" @input="handleSearch" />
				</view>
				<view class="my-platform-switch">
					<switch :checked="showMyPlatforms" @change="toggleMyPlatforms" color="#FF9757" style="transform: scale(0.8);" />
					<text>我的平台</text>
				</view>
			</view>

			<!-- 平台列表 -->
			<scroll-view scroll-y="true" class="platform-list" :show-scrollbar="false" refresher-enabled
				:refresher-triggered="refreshing" @refresherrefresh="onRefresh">
				<view v-if="loading" class="loading-container">
					<uni-icons type="spinner-cycle" size="30" color="#999"></uni-icons>
					<text class="loading-text">加载中...</text>
				</view>

				<template v-else>
					<view v-if="platformList.length === 0 && !showMyPlatforms" class="empty-container">
						<image class="empty-image" src="/static/images/empty.png" mode="aspectFit"></image>
						<text class="empty-text">暂无平台数据</text>
					</view>
					
					<view v-else-if="platformList.length === 0 && showMyPlatforms" class="empty-container">
						<image class="empty-image" src="/static/images/empty.png" mode="aspectFit"></image>
						<text class="empty-text">暂无平台数据</text>
						<view class="empty-add-btn" @click="showAddModal">
							<text>添加第一个平台</text>
						</view>
					</view>

					<view class="platform-group" v-else>
						<!-- 卡片式布局 -->
						<view class="platform-cards">
							<!-- 添加平台卡片 - 始终显示在第一个位置 -->
							<view class="platform-card add-card" @click="showAddModal" v-if="showMyPlatforms">
								<view class="platform-card-content">
									<view class="platform-icon add-icon">
										<uni-icons type="plus" size="30" color="#5E81F4"></uni-icons>
									</view>
									<text class="platform-name add-text">新增平台</text>
								</view>
							</view>
							
							<!-- 平台卡片列表 -->
							<view v-for="(item, index) in platformList" :key="item.id" class="platform-card">
								<view class="platform-card-content">
									<view class="platform-icon">
										<image :src="item.icon || '/static/images/default-platform.png'" mode="aspectFit"></image>
									</view>
									<text class="platform-name">{{ item.name }}</text>
									<view class="platform-status">
										<text :class="{ 'status-active': item.status === 1 }">{{ item.status === 1 ? '已启用' : '已禁用' }}</text>
									</view>
								</view>
								
								<view class="platform-actions" v-if="item.userId === currentUserId">
									<view class="action-btn" @click.stop="editPlatform(item)">
										<uni-icons type="compose" size="24" color="#5E81F4"></uni-icons>
									</view>
									<view class="action-btn" @click.stop="confirmDelete(item)">
										<uni-icons type="trash" size="24" color="#FF5A5F"></uni-icons>
									</view>
								</view>
							</view>
						</view>

						<!-- 加载更多 -->
						<view class="load-more" v-if="hasMore" @click="loadMore">加载更多</view>
						<view class="no-more" v-else>没有更多数据了</view>
					</view>
				</template>
			</scroll-view>

			<!-- 添加/编辑平台弹窗 -->
			<uni-popup ref="platformModal" type="center" style="z-index:999">
				<view class="modal-content">
					<view class="modal-header">
						<text class="modal-title">{{ isEdit ? '编辑平台' : '添加平台' }}</text>
						<view class="close-btn" @click="closeModal">
							<uni-icons type="close" size="20" color="#999"></uni-icons>
						</view>
					</view>

					<view class="modal-body">
						<view class="form-item">
							<text class="form-label">平台名称</text>
							<input class="form-input" v-model="platformForm.name" placeholder="请输入平台名称" maxlength="20" />
						</view>

						<view class="form-item">
							<text class="form-label">平台图标</text>
							<upload-file ref="uploadFile" v-model="platformForm.icon" folder-path="APP/PiggyBank/platform"
								placeholder="点击选择图标" :size="160" :image-only="true" :max-size="2" @change="handleFileChange" />
						</view>

						<view class="form-item">
							<text class="form-label">平台状态</text>
							<view class="status-selector">
								<view class="status-option" :class="{ active: platformForm.status === 1 }" @click="selectStatus(1)">
									<text>启用</text>
								</view>
								<view class="status-option" :class="{ active: platformForm.status === 0 }" @click="selectStatus(0)">
									<text>禁用</text>
								</view>
							</view>
						</view>
					</view>

					<view class="modal-footer">
						<view class="btn cancel-btn" @click="closeModal">取消</view>
						<view class="btn confirm-btn" @click="savePlatform">确认</view>
					</view>
				</view>
			</uni-popup>
		</view>
	</page-wrapper>
</template>

<script>
import { queryPlatforms, addPlatform, updatePlatform, deletePlatform, togglePlatformStatus } from '@/api/platform.js';
import { getUserInfo } from '@/api/user.js';
import { themeMixin } from '@/utils/theme.js';
import PageWrapper from '@/components/page-wrapper/page-wrapper.vue';
import UploadFile from '@/components/upload-file/upload-file.vue';

export default {
	components: {
		PageWrapper,
		UploadFile
	},
	mixins: [themeMixin],
	data() {
		return {
			navTitleStyle: {
				color: '#FFFFFF'
			},
			platformList: [], // 平台列表
			loading: true, // 加载状态
			refreshing: false, // 下拉刷新状态
			currentUserId: uni.getStorageSync('userId') || null, // 当前用户ID
			showMyPlatforms: true, // 是否只显示我的平台
			
			// 搜索表单
			searchForm: {
				name: '', // 平台名称
				userId: null, // 用户ID，用于筛选自己的平台
				page: 1,
				pageSize: 10
			},
			
			// 分页信息
			pagination: {
				current: 1,
				pages: 1,
				total: 0
			},
			hasMore: false, // 是否有更多数据
			
			// 当前操作的平台
			currentPlatform: null,
			
			// 平台表单
			platformForm: {
				name: '',
				icon: '',
				status: 1,
				userId: null
			},
			
			isEdit: false, // 是否为编辑模式
			selectedFile: null, // 用于存储选择的文件信息
		}
	},
	async onLoad() {
		await this.getCurrentUser();
		this.fetchPlatformList(true);
	},
	methods: {
		// 获取当前用户信息
		async getCurrentUser() {
			try {
				const res = await getUserInfo();
				if (res.data && (res.data.code === 1 || res.data.code === 200)) {
					this.currentUserId = res.data.data.id;
					this.searchForm.userId = this.showMyPlatforms ? this.currentUserId : null;
					this.platformForm.userId = this.currentUserId;
				} else {
					uni.showToast({
						title: '获取用户信息失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取用户信息失败:', error);
				uni.showToast({
					title: '获取用户信息失败',
					icon: 'none'
				});
			}
		},
		
		// 获取平台列表
		async fetchPlatformList(isRefresh = false) {
			if (isRefresh) {
				this.searchForm.page = 1;
				this.loading = true;
			}
			
			try {
				const params = {
					...this.searchForm,
					userId: this.showMyPlatforms ? this.currentUserId : null
				};
				
				const res = await queryPlatforms(params);
				if (res.data && (res.data.code === 1 || res.data.code === 200)) {
					const { records, total, size, current, pages } = res.data.data;
					
					if (isRefresh) {
						// 刷新时替换数据
						this.platformList = records || [];
					} else {
						// 加载更多时追加数据
						this.platformList = [...this.platformList, ...(records || [])];
					}
					
					// 更新分页信息
					this.pagination = {
						current,
						pages,
						total
					};
					
					// 判断是否还有更多数据
					this.hasMore = current < pages;
				} else {
					uni.showToast({
						title: '获取平台失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取平台列表失败:', error);
				uni.showToast({
					title: '获取平台失败',
					icon: 'none'
				});
			} finally {
				this.loading = false;
				if (isRefresh) {
					this.refreshing = false;
				}
			}
		},
		
		// 处理搜索
		handleSearch() {
			clearTimeout(this._searchTimer);
			this._searchTimer = setTimeout(() => {
				this.searchForm.page = 1;
				this.fetchPlatformList(true);
			}, 300);
		},
		
		// 切换我的平台显示
		toggleMyPlatforms() {
			this.showMyPlatforms = !this.showMyPlatforms;
			this.searchForm.userId = this.showMyPlatforms ? this.currentUserId : null;
			this.searchForm.page = 1;
			this.fetchPlatformList(true);
		},
		
		// 下拉刷新
		async onRefresh() {
			this.refreshing = true;
			await this.fetchPlatformList(true);
		},
		
		// 加载更多
		loadMore() {
			if (this.hasMore) {
				this.searchForm.page += 1;
				this.fetchPlatformList(false);
			}
		},
		
		// 显示添加平台弹窗
		showAddModal() {
			this.isEdit = false;
			this.platformForm = {
				name: '',
				icon: '',
				status: 1,
				userId: this.currentUserId
			};
			this.selectedFile = null;
			this.$refs.platformModal.open();
		},
		
		// 编辑平台
		editPlatform(platform) {
			this.isEdit = true;
			this.currentPlatform = platform;
			this.platformForm = {
				id: platform.id,
				name: platform.name,
				icon: platform.icon,
				status: platform.status,
				userId: platform.userId
			};
			this.selectedFile = null;
			this.$refs.platformModal.open();
		},
		
		// 关闭弹窗
		closeModal() {
			this.$refs.platformModal.close();
		},
		
		// 选择状态
		selectStatus(status) {
			this.platformForm.status = status;
		},
		
		// 处理文件选择变化
		handleFileChange(fileInfo) {
			// 保存文件信息，但不立即上传
			this.selectedFile = fileInfo;
		},
		
		// 保存平台
		async savePlatform() {
			if (!this.platformForm.name.trim()) {
				uni.showToast({
					title: '请输入平台名称',
					icon: 'none'
				});
				return;
			}
			
			try {
				uni.showLoading({
					title: '保存中...',
					mask: true
				});
				
				// 如果有新选择的文件，先上传
				if (this.selectedFile?.tempFile) {
					try {
						// 获取上传组件的引用
						const uploadComponent = this.$refs.uploadFile;
						// 执行上传
						const fileUrl = await uploadComponent.upload();
						// 更新表单数据
						this.platformForm.icon = fileUrl;
					} catch (error) {
						uni.hideLoading();
						uni.showToast({
							title: '文件上传失败',
							icon: 'none'
						});
						return;
					}
				}
				
				// 执行保存操作
				let res;
				if (this.isEdit) {
					res = await updatePlatform(this.platformForm);
				} else {
					res = await addPlatform(this.platformForm);
				}
				
				if (res.data && (res.data.code === 1 || res.data.code === 200)) {
					uni.showToast({
						title: this.isEdit ? '编辑成功' : '添加成功',
						icon: 'success'
					});
					this.closeModal();
					this.fetchPlatformList(true);
				} else {
					uni.showToast({
						title: res.data?.msg || (this.isEdit ? '编辑失败' : '添加失败'),
						icon: 'none'
					});
				}
			} catch (error) {
				console.error(this.isEdit ? '编辑平台失败:' : '添加平台失败:', error);
				uni.showToast({
					title: this.isEdit ? '编辑失败' : '添加失败',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
			}
		},
		
		// 切换平台状态
		async toggleStatus(platform) {
			try {
				uni.showLoading({
					title: '处理中...',
					mask: true
				});
				
				const res = await togglePlatformStatus(platform.id);
				if (res.data && (res.data.code === 1 || res.data.code === 200)) {
					// 更新本地状态
					const index = this.platformList.findIndex(item => item.id === platform.id);
					if (index !== -1) {
						this.platformList[index].status = this.platformList[index].status === 1 ? 0 : 1;
					}
					
					uni.showToast({
						title: this.platformList[index].status === 1 ? '已启用' : '已禁用',
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: res.data?.msg || '操作失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('切换平台状态失败:', error);
				uni.showToast({
					title: '操作失败',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
			}
		},
		
		// 确认删除平台
		confirmDelete(platform) {
			this.currentPlatform = platform;
			uni.showModal({
				title: '删除平台',
				content: '确定要删除该平台吗？删除后无法恢复。',
				success: res => {
					if (res.confirm) {
						this.deletePlatform();
					}
				}
			});
		},
		
		// 删除平台
		async deletePlatform() {
			if (!this.currentPlatform) return;
			
			try {
				uni.showLoading({
					title: '删除中...',
					mask: true
				});
				
				const res = await deletePlatform(this.currentPlatform.id);
				if (res.data && (res.data.code === 1 || res.data.code === 200)) {
					uni.showToast({
						title: '删除成功',
						icon: 'success'
					});
					
					// 从列表中移除
					const index = this.platformList.findIndex(item => item.id === this.currentPlatform.id);
					if (index !== -1) {
						this.platformList.splice(index, 1);
					}
				} else {
					uni.showToast({
						title: res.data?.msg || '删除失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('删除平台失败:', error);
				uni.showToast({
					title: '删除失败',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
				this.currentPlatform = null;
			}
		}
	}
}
</script>

<style lang="scss">
.platform-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: $background-color;
	
	// 搜索筛选区
	.search-filter {
		padding: 20rpx 30rpx;
		background-color: #FFFFFF;
		display: flex;
		align-items: center;
		box-shadow: $shadow-small;
		position: sticky;
		top: 0;
		z-index: 10;
		
		.search-box {
			flex: 1;
			height: 70rpx;
			background-color: #F5F5F5;
			border-radius: 35rpx;
			display: flex;
			align-items: center;
			padding: 0 30rpx;
			margin-right: 20rpx;
			transition: all 0.3s;
			
			&:focus-within {
				box-shadow: 0 0 0 2rpx rgba($primary-color, 0.2);
			}
			
			input {
				flex: 1;
				height: 100%;
				font-size: $font-size-medium;
				margin-left: 10rpx;
			}
		}
		
		.my-platform-switch {
			display: flex;
			align-items: center;
			padding: 0 10rpx;
			
			text {
				font-size: $font-size-small;
				color: $text-color;
				margin-left: 10rpx;
			}
		}
	}
	
	// 平台列表
	.platform-list {
		flex: 1;
		padding: 20rpx;
		box-sizing: border-box;
		
		// 卡片式布局
		.platform-cards {
			display: flex;
			flex-wrap: wrap;
			margin: 0 -10rpx;
			
			// 平台卡片
			.platform-card {
				width: calc(33.33% - 20rpx);
				margin: 10rpx;
				background-color: #FFFFFF;
				border-radius: 16rpx;
				overflow: hidden;
				box-shadow: $shadow-small;
				position: relative;
				transition: all 0.3s;
				display: flex;
				flex-direction: row;
				
				&:active {
					transform: scale(0.98);
				}
				
				// 平台卡片内容
				.platform-card-content {
					padding: 20rpx 0 20rpx 20rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					min-height: 200rpx;
					flex: 3;
				}
				
				// 平台图标
				.platform-icon {
					width: 80rpx;
					height: 80rpx;
					border-radius: 16rpx;
					overflow: hidden;
					margin-bottom: 16rpx;
					background-color: #F5F5F5;
					box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
					
					image {
						width: 100%;
						height: 100%;
						object-fit: cover;
					}
				}
				
				// 平台名称
				.platform-name {
					font-size: 28rpx;
					color: $text-color;
					font-weight: 500;
					text-align: center;
					margin-bottom: 8rpx;
					word-break: break-all;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
					overflow: hidden;
					width: 100%;
				}
				
				// 平台状态
				.platform-status {
					font-size: 24rpx;
					color: $text-color-light;
					
					.status-active {
						color: $success-color;
					}
				}
				
				// 平台操作按钮
				.platform-actions {
					display: flex;
					flex-direction: column;
					justify-content: center;
					// border-left: 1rpx solid $border-color;
					flex: 1;
					
					.action-btn {
						flex: 1;
						display: flex;
						justify-content: center;
						align-items: center;
						transition: all 0.2s;
						
						&:active {
							background-color: rgba($primary-color, 0.1);
						}
						
						&:not(:last-child) {
							// border-bottom: 1rpx solid $border-color;
						}
					}
				}
				
				// 添加平台卡片
				&.add-card {
					box-sizing: border-box;
					border: 2rpx dashed rgba($primary-color, 0.3);
					background-color: rgba($primary-color, 0.02);
					
					.platform-icon.add-icon {
						background-color: rgba($primary-color, 0.1);
						display: flex;
						align-items: center;
						justify-content: center;
					}
					
					.platform-name.add-text {
						color: $primary-color;
						font-weight: 500;
					}
					
					&:active {
						background-color: rgba($primary-color, 0.05);
					}
				}
			}
		}
		
		// 加载中
		.loading-container {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 100rpx 0;
			
			.loading-text {
				margin-top: 20rpx;
				font-size: $font-size-small;
				color: $text-color-light;
			}
		}
		
		// 空状态
		.empty-container {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 100rpx 0;
			
			.empty-image {
				width: 200rpx;
				height: 200rpx;
				margin-bottom: 30rpx;
				opacity: 0.7;
			}
			
			.empty-text {
				font-size: $font-size-medium;
				color: $text-color-light;
				margin-bottom: 30rpx;
			}
			
			.empty-add-btn {
				padding: 20rpx 40rpx;
				background-color: $primary-color;
				border-radius: 40rpx;
				box-shadow: 0 4rpx 12rpx rgba($primary-color, 0.3);
				transition: all 0.3s;
				
				text {
					font-size: $font-size-medium;
					color: #FFFFFF;
					font-weight: 500;
				}
				
				&:active {
					transform: scale(0.98);
					opacity: 0.9;
				}
			}
		}
		
		// 加载更多
		.load-more,
		.no-more {
			text-align: center;
			padding: 30rpx 0;
			color: $text-color-light;
			font-size: $font-size-small;
		}
		
		.load-more {
			position: relative;
			
			&::after {
				content: '';
				position: absolute;
				bottom: 20rpx;
				left: 50%;
				transform: translateX(-50%);
				width: 100rpx;
				height: 2rpx;
				background: linear-gradient(to right, transparent, $text-color-light, transparent);
			}
		}
	}
	
	// 弹窗样式
	.modal-content {
		width: 650rpx;
		background-color: #FFFFFF;
		border-radius: 20rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
		
		.modal-header {
			padding: 30rpx;
			border-bottom: 1rpx solid $border-color;
			display: flex;
			justify-content: space-between;
			align-items: center;
			
			.modal-title {
				font-size: $font-size-large;
				font-weight: bold;
				color: $text-color;
			}
			
			.close-btn {
				width: 60rpx;
				height: 60rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				border-radius: 50%;
				transition: all 0.2s;
				
				&:active {
					background-color: #F5F5F5;
				}
			}
		}
		
		.modal-body {
			padding: 30rpx;
			
			.form-item {
				margin-bottom: 30rpx;
				
				.form-label {
					font-size: $font-size-medium;
					color: $text-color;
					margin-bottom: 16rpx;
					display: block;
				}
				
				.form-input {
					width: 100%;
					height: 80rpx;
					border: 1rpx solid $border-color;
					border-radius: 8rpx;
					padding: 0 20rpx;
					font-size: $font-size-medium;
					color: $text-color;
					transition: all 0.3s;
					
					&:focus {
						border-color: $primary-color;
						box-shadow: 0 0 0 2rpx rgba($primary-color, 0.1);
					}
				}
				
				// 状态选择器
				.status-selector {
					display: flex;
					
					.status-option {
						flex: 1;
						height: 80rpx;
						display: flex;
						justify-content: center;
						align-items: center;
						border: 1rpx solid $border-color;
						margin: 0 10rpx;
						border-radius: 8rpx;
						font-size: $font-size-medium;
						color: $text-color;
						transition: all 0.3s;
						
						&:first-child {
							margin-left: 0;
						}
						
						&:last-child {
							margin-right: 0;
						}
						
						&.active {
							border-color: $primary-color;
							background-color: rgba($primary-color, 0.1);
							color: $primary-color;
						}
					}
				}
			}
		}
		
		.modal-footer {
			padding: 30rpx;
			border-top: 1rpx solid $border-color;
			display: flex;
			justify-content: flex-end;
			
			.btn {
				flex: 1;
				height: 70rpx;
				border-radius: 35rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: $font-size-medium;
				margin-left: 20rpx;
				transition: all 0.3s;
				
				&.cancel-btn {
					background-color: #F5F5F5;
					color: $text-color;
					
					&:active {
						background-color: #E0E0E0;
					}
				}
				
				&.confirm-btn {
					background-color: $primary-color;
					color: #FFFFFF;
					
					&:active {
						opacity: 0.9;
						transform: scale(0.98);
					}
				}
			}
		}
	}
}

// 添加进入动画
@keyframes fadeIn {
	from {
		opacity: 0;
		transform: translateY(20rpx);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

.platform-card {
	animation: fadeIn 0.3s ease-out forwards;
}

// 为卡片添加交错动画
@for $i from 1 through 10 {
	.platform-card:nth-child(#{$i}) {
		animation-delay: #{$i * 0.05}s;
	}
}
</style> 